package com.bestcem.xm.txtanls.controller;


import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.txtanls.grpc.service.param.worktable.ListWorktableParam;
import com.bestcem.xm.txtanls.service.WorktableService;
import com.bestcem.xm.txtanls.service.dto.worktable.WorktableFromBIDTO;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;

/**
 * 数据源controller类
 *
 * @author liheng
 * @version v2.0
 * @date 2021/8/5 20:31
 */
@RestController
@RequestMapping(value = "/txtanls/worktables", produces = MediaType.APPLICATION_JSON_VALUE)
public class WorktableController {

    @Resource
    private WorktableService worktableService;


    /**
     * 获取数据源详情
     *
     * @param id 数据源id
     * @return 返回数据源list（为了适配前端）
     */

    @GetMapping(value = "/{id}")
    public XmResultJson<List<WorktableFromBIDTO>> getWorktable(@PathVariable(value = "id") String id) {

        if (!ObjectId.isValid(id)) {
            // id错误
            return XmResultJson.fail(4, "缺少话题id");
        }
        ServiceResult<WorktableFromBIDTO> result = worktableService.getWorktable(id);
        if (result.isSuccess()) {
            return XmResultJson.success(Collections.singletonList(result.getData()));
        } else {
            return XmResultJson.fail(5, result.getMsg());
        }
    }

    /**
     * 获取用户可用数据源list
     *
     * @return 数据源list
     */

    @GetMapping(value = "/")
    public XmResultJson<List<WorktableFromBIDTO>> listWorktable(HttpServletRequest request) {
        
        
        String orgId = SecurityContextHolder.getOrgId();
        String userId = SecurityContextHolder.getUserId();
        if (StringUtils.isAnyBlank(orgId, userId)) {
            return XmResultJson.fail(4, "userId或orgId错误");
        }
        ServiceResult<List<WorktableFromBIDTO>> result = worktableService.listWorktable(new ListWorktableParam(orgId, userId));
        if (result.isSuccess()) {
            return XmResultJson.success(result.getData());
        } else {
            return XmResultJson.fail(5, result.getMsg());
        }

    }
}
